package com.yxq.mdt.app.base;


import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.ibase.IBaseContract;

import java.util.List;

import io.reactivex.Observable;

/**
 * 通用列表activity，处理下拉刷新，上啦加载更多，分页逻辑等
 */
public abstract class BaseListActivity<P extends IBaseContract.IBasePresenter, T, VH extends BaseViewHolder> extends BaseActivity<P> {

    public static final String TAG = "BaseListFragment";

    protected CommonTitleBar mCommonTitleBar;
    protected ImageView mBackImage;
    protected RecyclerView mRecyclerView;
    protected SmartRefreshLayout mRefreshLayout;
    protected BaseQuickAdapter<T, VH> mRecycleViewAdapter;
    protected boolean canLoadMore = false;
    protected Observable<Integer> observable;


    /**
     * 没有数据时候的空白页面
     */
    protected View mEmptyView;

    /**
     * 当前的页码
     */
    protected int mCurrentPage = 1;

    public abstract View getEmptyView();

    @Override
    public int getLayoutId() {
        return R.layout.base_activity_list_layout;
    }

    protected abstract BaseQuickAdapter<T, VH> getRecycleViewAdapter();

    public abstract void onLoadData(int pageIndex);

    public void onBackClick() {
        finish();
    }

    public void setTitleBarCenterText(String titleBarCenterText) {
        if (mCommonTitleBar != null && !TextUtils.isEmpty(titleBarCenterText)) {
            mCommonTitleBar.getCenterTextView().setText(titleBarCenterText);
        }
    }

    @Override
    public void initView() {

        mCommonTitleBar = findViewById(R.id.titlebar);
        if (mCommonTitleBar != null) {
            mCommonTitleBar.setListener((v, action, extra) -> {
                if (action == CommonTitleBar.ACTION_LEFT_BUTTON) {
                    finish();
                }
            });
        }

        mRefreshLayout = findViewById(R.id.srl_refreshLayout);

        mRecyclerView = findViewById(R.id.rcv_recycler_view);
        mRecyclerView.setHasFixedSize(isFixItem());

        if (canRefresh()) {
            mRefreshLayout.setOnRefreshListener(refreshLayout -> {
                mCurrentPage = 1;
                onLoadData(mCurrentPage);
            });
        } else {
            mRefreshLayout.setEnableRefresh(false);
        }

        if (canLoadMore()) {
            mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
                mCurrentPage++;
                onLoadData(mCurrentPage);
            });
        } else {
            mRefreshLayout.setEnableLoadMore(false);
        }


        if (mRecycleViewAdapter == null) {
            mRecycleViewAdapter = getRecycleViewAdapter();
        }
        mRecyclerView.setAdapter(mRecycleViewAdapter);

        RecyclerView.ItemDecoration itemDecoration = getItemDecoration();
        if (itemDecoration != null) {
            mRecyclerView.addItemDecoration(getItemDecoration());
        }
        mRecyclerView.setLayoutManager(getLayoutManager());


        mEmptyView = getEmptyView();
        if (mEmptyView != null) {
            mEmptyView.setOnClickListener(v -> {
                loadContentData();
            });
        }


        if (isNeedAutoRefresh()) {
            //startLoadingAnimation();
            onLoadData(mCurrentPage);
        }
    }

    /**
     * 设置返回按钮的图片，
     *
     * @param backImage
     */
    public void setTitleBackImage(int backImage) {
        mBackImage.setImageResource(backImage);
    }

    /**
     * 需要在子类中主动去调用该方法来获取数据
     */
    protected void loadContentData() {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.GONE);
        }

        //加载数据
        onRefreshView();
    }


    /**
     * 在处理List 中 第一页就没有数据，会自动调用
     */
    protected void showEmptyLayout() {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.VISIBLE);

            mRecycleViewAdapter.setEmptyView(mEmptyView);

        }
    }

    /**
     * 隐藏空页面
     */
    protected void hideEmptyLayout() {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(View.GONE);
        }
    }

    /**
     * 统一处理 List 数据
     *
     * @param listData 返回的数据
     */
    protected void handleListData(final List<T> listData) {
        try {
            if (mCurrentPage > 1) {
                mRefreshLayout.finishLoadMore();
                if (listData != null && listData.size() != 0) {
                    mRecycleViewAdapter.addData(listData);
                } else {
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                }

            } else {
                if (listData != null && listData.size() != 0) {
                    mRecycleViewAdapter.setNewData(listData);
                    mRecycleViewAdapter.notifyDataSetChanged();
                    hideEmptyLayout();
                } else {
                    mRecycleViewAdapter.setNewData(null);
                    mRefreshLayout.setEnableLoadMore(false);
                    showEmptyLayout();
                }
                mRefreshLayout.finishRefresh();
            }

            mRecycleViewAdapter.notifyLoadMoreToLoading();
            onHideLoading();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(this, RecyclerView.VERTICAL, false);

    }

    protected RecyclerView.ItemDecoration getItemDecoration() {
        //return new SpacesItemDecoration(0, ConvertUtils.dp2px(8), getResources().getColor(R.color.app_color_window_background));
        return null;
    }

    /**
     * 提供重写 设置是否 下拉刷新
     */
    protected boolean canRefresh() {
        return true;
    }

    /**
     * 提供重写 设置是否 上拉加载
     */
    protected boolean canLoadMore() {
        return true;
    }


    protected boolean isNeedAutoRefresh() {
        return false;
    }

    /**
     * 列表中的item布局是否一致，可以提高效率
     */
    protected boolean isFixItem() {
        return true;
    }


    public void onShowLoading() {
        //TODO 这里应该是放页面中间的加载动画
        //showLoadingDialog();
    }

    public void onHideLoading() {
        mRefreshLayout.post(() -> {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadMore();
        });
        hideLoadingDialog();
    }


    public void onShowNetError() {
        runOnUiThread(() -> {
            if (mRecycleViewAdapter.getData().size() <= 0) {
                mEmptyView.setVisibility(View.VISIBLE);
            } else {
                mEmptyView.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //onRefreshView();
    }

    protected void onRefreshView() {
        onShowLoading();
        mCurrentPage = 1;
        onLoadData(mCurrentPage);
    }


    public void onShowNoMore() {
        mRefreshLayout.finishLoadMoreWithNoMoreData();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
